const path = require("path");
const db = require("../db/index");
const fs = require("fs");

// 获取文章分类
exports.getArticlesCates = (req, res) => {
  console.log(req.auth, 200);
  const { pageNo = 1, pageSize = 5, articleType = "", alias = "" } = req.body;
  let baseSql = "select * from ev_article_cate";
  const querysArr = [];
  const valueArr = [];

  if (articleType) {
    querysArr.push(`name like ?`);
    valueArr.push(`%${articleType}%`);
  }
  if (alias) {
    querysArr.push(`alias like?`);
    valueArr.push(`%${alias}%`);
  }

  if (querysArr.length > 0) {
    baseSql += " where " + querysArr.join(" and ");
  }

  db.query(baseSql, valueArr, (err, data) => {
    if (err) return res.cc(err);
    const total = data.length;
    baseSql += " limit ?,?";
    db.query(
      baseSql,
      [...valueArr, (pageNo - 1) * pageSize, pageSize],
      (err, results) => {
        if (err) return res.cc(err);
        res.send({
          status: 0,
          message: "获取文章分类成功",
          data: results,
          total,
          pageNo: parseInt(pageNo),
          pageSize: parseInt(pageSize),
        });
      }
    );
  });
};

// 删除文章分类
exports.deleteCateById = (req, res) => {
  // 先查询要删除的记录，获取文件路径
  const querySql = `select * from ev_article_cate where id=?`;
  db.query(querySql, req.body.id, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("文章分类不存在");

    const fileInfo = results[0]; // 保存文件信息

    // 先删除数据库记录
    const deleteSql = `delete from ev_article_cate where id=?`;
    db.query(deleteSql, req.body.id, (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) return res.cc("删除文章分类失败");

      // 数据库记录删除成功后，再删除物理文件
      if (fileInfo.cover_img) {
        const filePath = path.join(__dirname, "../public", fileInfo.cover_img);
        if (fs.existsSync(filePath)) {
          try {
            fs.unlinkSync(filePath);
          } catch (error) {
            console.error("文件删除失败:", error);
            // 即使文件删除失败，数据库记录已经删除成功，仍然返回成功
          }
        }
      }

      res.cc("删除文章分类成功", 0);
    });
  });
};

// 添加文章分类
exports.addCate = (req, res) => {
  const countSql = `select * from ev_article_cate where name=?`;
  db.query(countSql, req.body.name, (err, results) => {
    if (err) return res.cc(err);
    if (results.length >= 1) return res.cc("文章分类已存在");

    // 构建要插入的数据
    const articleData = {
      name: req.body.name,
      alias: req.body.alias,
      cover_img: req.file ? `/uploads/${req.file.filename}` : "", // 存储文件路径
    };

    const sql = `insert into ev_article_cate set ?`;
    db.query(sql, articleData, (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) return res.cc("新增文章分类失败");
      res.cc("新增文章分类成功", 0);
    });
  });
};

/* 
exports.addCate = (req, res) => {
  // 打印上传的文件信息和表单数据，用于调试
  console.log('上传的文件:', req.files);
  console.log('表单数据:', req.body);

  const countSql = `select * from ev_article_cate where name=?`;
  db.query(countSql, req.body.name, (err, results) => {
    if (err) return res.cc(err);
    if (results.length >= 1) return res.cc("文章分类已存在");

    // 获取所有文件的路径
    const fileUrls = req.files ? req.files.map(file => `/uploads/${file.filename}`) : [];
    
    // 构建要插入的数据
    const articleData = {
      name: req.body.name,
      alias: req.body.alias,
      // 将多个文件路径以逗号分隔存储
      cover_img: fileUrls.join(',')
    };

    const sql = `insert into ev_article_cate set ?`;
    db.query(sql, articleData, (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) return res.cc("新增文章分类失败");
      
      // 返回成功信息，包含上传的文件路径
      res.send({
        status: 0,
        message: "新增文章分类成功",
        data: {
          ...articleData,
          id: results.insertId
        }
      });
    });
  });
};
*/

exports.downloadFile = (req, res) => {
  console.log(req.body.id);
  // res.send("下载成功");
  const sql = `select * from ev_article_cate where id=?`;
  db.query(sql, req.body.id, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("文件不存在");
    // 在这个路径下 找到这个文件
    const filePath = path.join(__dirname, "../public", results[0].cover_img);
    res.download(filePath);
  });
};
